package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.constant.JSBSpecialID;
import com.jsb.laundry.common.enums.OrderStatus;
import com.jsb.laundry.common.enums.ProductType;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.dao.OrderDao;
import com.jsb.laundry.model.entity.ActivityModuleDetail;
import com.jsb.laundry.model.entity.PayOrderInfo;
import com.jsb.laundry.model.entity.WxRiderList;
import com.jsb.laundry.model.entity.WxSend;
import com.jsb.laundry.service.impl.WxSendServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 各个方法写入
 */
@Component
public class BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);

    @Resource
    private OrderDao orderDao;


    /**
     * 构建月卡数据
     *
     * @param activityId
     * @param userId
     * @param payId
     * @return
     */
    static List buildMonthCardData(String activityId, String userId, String payId) {
        List list = new ArrayList();
        if (JSBSpecialID.JSB_MONTH_1_298.equals(activityId)) { //298只有15张衣物卡券
            for (int i = 0; i < 15; i++) {
                HashMap hashMap = new HashMap();
                hashMap.put("activityId", activityId);
                hashMap.put("userId", userId);
                hashMap.put("payId", payId);
                hashMap.put("cardType", "0");
                hashMap.put("cardTag", "*一套夏季衣服(上衣、裤子等)");
                hashMap.put("cardTitle", "聚洗衣抵用券");
                hashMap.put("beginTime", Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()));
                hashMap.put("endTime", Date.from(LocalDate.now().plusMonths(1).atStartOfDay(ZoneId.systemDefault()).toInstant()));// 添加一个月
                list.add(hashMap);
            }
        } else if (JSBSpecialID.JSB_MONTH_2_398.equals(activityId)) { //398有10张衣物卡券、鞋子卡券5张
            for (int i = 0; i < 15; i++) {
                HashMap hashMap = new HashMap();
                hashMap.put("activityId", activityId);
                hashMap.put("userId", userId);
                hashMap.put("payId", payId);
                if (i < 5) {
                    hashMap.put("cardType", "1");
                    hashMap.put("cardTag", "*一套夏季衣服(上衣、裤子、鞋等)");
                } else {
                    hashMap.put("cardType", "0");
                    hashMap.put("cardTag", "*一套夏季衣服(上衣、裤子等)");
                }
                hashMap.put("cardTitle", "聚洗衣抵用券");
                hashMap.put("beginTime", Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()));
                hashMap.put("endTime", Date.from(LocalDate.now().plusMonths(1).atStartOfDay(ZoneId.systemDefault()).toInstant()));// 添加一个月
                list.add(hashMap);
            }
        }
        return list;
    }


    /**
     * 校服处理逻辑 填充school_record
     */
    List<ActivityModuleDetail> schoolDeal(ActivityModuleDetail preOrderInfo) {
        LOGGER.info("校服处理:{}", preOrderInfo);
        LocalDate nextAppointmentTime = getNextSchoolAppointmentTime();
        List<ActivityModuleDetail> details = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            ActivityModuleDetail detail = new ActivityModuleDetail();
            detail.setUserId(preOrderInfo.getUserId());
            detail.setPayId(preOrderInfo.getOrderId());
            Date date = Date.from(nextAppointmentTime.atStartOfDay().plusDays(i * 7).atZone(ZoneId.systemDefault()).toInstant());
            detail.setAppointmentTime(date);
            details.add(detail);
        }
        details.remove(0);
        return details;
    }

    /**
     * 获取下次校服下单的时间
     *
     * @return
     */
    private static LocalDate getNextSchoolAppointmentTime() {
        LocalDate nextFriday = getNextFriday();
        long between = ChronoUnit.DAYS.between(LocalDate.now().plusDays(0), nextFriday);
        if (Math.abs(between) <= 5) {
            nextFriday = nextFriday.plusDays(7);
        }
        return nextFriday;
    }

    /**
     * 获取当前日期后第一个星期五
     *
     * @return
     */
    private static LocalDate getNextFriday() {
        LocalDate currentDate = LocalDate.now().plusDays(0);
        LocalDate thisFriday = currentDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY));

        if (currentDate.isBefore(thisFriday)) {
            return thisFriday;
        } else {
            LocalDate nextFriday = currentDate.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
            return nextFriday;
        }
    }


    /**
     * 获取商品所属类型枚举
     *
     * @param productId
     * @return
     */
    public static String getProductType(List<String> productId) {
        String res = "";
        if (productId.size() == 0) {
            return res;
        }
        if (JSBSpecialID.VIP_BUY.containsAll(productId)) {
            res = ProductType.VIP_BUY.name();
        } else if (JSBSpecialID.ACTIVITY_LIST_ID.containsAll(productId)) {
            res = ProductType.ACTIVITY.name();
        } else if (JSBSpecialID.SCHOOL_MONTH.containsAll(productId)) {
            res = ProductType.SCHOOL_MONTH.name();
        } else if (JSBSpecialID.MONTH_CARD.containsAll(productId)) {
            res = ProductType.MONTH_CART.name();
        } else {
            res = ProductType.CART.name();
        }
        return res;
    }

    /**
     * 订单id生成
     *
     * @param productId
     * @return
     */
    public static String getOrderId(List<String> productId) {
        String orderId = "";
        if (productId.size() == 0) {
            return orderId;
        }
        if (JSBSpecialID.VIP_BUY.containsAll(productId)) {
            orderId = ProductType.VIP_BUY.name();
        } else if (JSBSpecialID.ACTIVITY_LIST_ID.containsAll(productId)) {
            orderId = ProductType.ACTIVITY.name();
        } else if (JSBSpecialID.SCHOOL_MONTH.containsAll(productId)) {
            orderId = ProductType.SCHOOL_MONTH.name();
        } else if (JSBSpecialID.MONTH_CARD.containsAll(productId)) {
            orderId = ProductType.MONTH_CART.name();
        } else {
            orderId = ProductType.CART.name();
        }
        return orderId;
    }


    /**
     * 订单状态变更日志
     *
     * @param orderId
     * @param status
     */
    public void addOrderStatusLog(String orderId, OrderStatus status, String orderDirection) {
        int var0 = orderDao.addOrderStatusLog(orderId, status.getCode(), status.getMsg(), orderDirection);
        LOGGER.info("订单:{},状态变更日志:{},订单方向:{}", orderId, status, orderDirection);
    }


    /**
     * 推送通知给用户
     *
     * @param openId
     * @param orderId
     */
    public void paymentNoticeUser(String openId, String orderId) {
        LOGGER.info("推送通知给用户openId{},orderId{}",openId,orderId);
        PayOrderInfo bySendInfo = orderDao.findBySendInfo(orderId);
        WxSend wxSend = new WxSend();
        wxSend.setStatus(1);//推给用户标识
        wxSend.setTime10(JSBUtil.dateFormat(bySendInfo.getPayTime()));//预约时间

//        wxSend.setThing2(bySendInfo.getGoodsTitle());//订单内容
        wxSend.setAmount8(JSBUtil.turnDoubleStr(bySendInfo.getOriginalPay()) + "元");//原价金额
        wxSend.setAmount26(JSBUtil.turnDoubleStr(bySendInfo.getActuallyPay()) + "元");//实际支付金额
        wxSend.setOpenId(openId);
        wxSend.setCharacter_string22(orderId);
        wxSend.setTemplateId("9P2rnYPa_Zmt-FEw_yQRD0znVD0Wj2setYBTWWl5M_c");
        WxSendServiceImpl.send(wxSend);
    }

    /**
     * 推送通知给骑手
     *
     * @param orderId
     */
    void paymentNoticeRider(String orderId) {
        LOGGER.info("推送通知给骑手orderId{}",orderId);
        PayOrderInfo bySendInfo = orderDao.findBySendInfo(orderId);

        Matcher matcher = Pattern.compile("\\D").matcher(orderId);// 匹配非数字字符
        String payId = matcher.replaceAll("");

        //微信公众号推送骑手
        JSONObject time13 = new JSONObject();
        JSONObject thing2 = new JSONObject();
        JSONObject character_string8 = new JSONObject();
        JSONObject object = new JSONObject();
        object.put("character_string8", character_string8);
        object.put("time13", time13);
        character_string8.put("value", payId);//订单号  int类型
        time13.put("value", JSBUtil.dateFormat(new Date()));//下单时间

        //获取骑手openid,下单成功给所有表骑手用户发送通知
        List<WxRiderList> byqOpenId = orderDao.findByqOpenId();

        if ("1".equals(bySendInfo.getSendType())) {
            for (WxRiderList wxRiderList : byqOpenId) {
                WxSendServiceImpl.sendLaundry(object, wxRiderList.getOpenId());
            }
        }

    }

    /**
     * 资金入公司账户
     *
     * @param url     资金接口路径
     * @param orderId 订单id
     * @param total   实际支付金额
     */
    void fundIntoCompanyAccount(String url, String orderId, int total) {
        LOGGER.info("资金入公司账户:orderId:{},total:{}", orderId, total);
        Map map = new HashMap();
        map.put("orderId", orderId);
        map.put("money", total);
        HttpUtil.sendPost(url, null, JSONObject.toJSONString(map));
    }


    /**
     * 用户支付后，若是被骑手邀请进入的，就给骑手分佣
     *
     * @param orderId   订单id
     * @param userId    用户id
     * @param orderType 订单分佣金额存入类型 ( (1) deposit_freeze 入待结算 (2)deposit 入已结算  )
     */
    void giveRiderCommission(String orderId, String userId, String orderType) {
        LOGGER.info("用户支付后，若是被骑手邀请进入的，就给骑手分佣:orderId:{},userId:{},orderType:{}", orderId, userId,orderType);
        //骑手id(用户的邀请人)，是否被骑手邀请进来，有就给邀请骑手分佣
        String riderPromotionId = orderDao.getRiderPromotion(userId);
        //被骑手邀请进来的，调用分佣
        if (!JSBUtil.isEmptyString(riderPromotionId)) {
            Map<String, String> map = new HashMap();
            map.put("orderId", orderId);
            map.put("riderId", riderPromotionId);
            map.put("ledgerType", orderType);
            HttpUtil.sendPost("http://127.0.0.1:20000/riderOrder/serve/agencyCommission", null, JSONObject.toJSONString(map));
        }
    }


}
